<template>
  <a-drawer
    title="新增服务分类"
    :maskClosable="false"
    width=650
    placement="right"
    :closable="false"
    @close="onClose"
    :visible="categoryAddVisiable"
    style="height: calc(100% - 55px);overflow: auto;padding-bottom: 53px;">
    <a-form :form="form">
      <a-form-item label='分类名称' v-bind="formItemLayout">
        <a-input v-model="category.name"
                 v-decorator="['name',
                   {rules: [
                    { required: true, message: '不能为空'},
                    { max: 30, message: '长度不能超过30个字符'}
                  ]}]"/>
      </a-form-item>
      <a-form-item label='优先级' v-bind="formItemLayout">
        <a-input-number v-model="category.priority" :min="0"  style="width: 100%"
                        v-decorator="['priority',
                   {rules: [
                    { required: true, message: '不能为空'}
                  ]}]"/>
      </a-form-item>
      <a-form-item label='状态' v-bind="formItemLayout">
        <a-switch defaultChecked :checked="enable.status" @change="statusChange"/>
      </a-form-item>
    </a-form>
    <div class="drawer-bootom-button">
      <a-popconfirm title="确定放弃编辑？" @confirm="onClose" okText="确定" cancelText="取消">
        <a-button style="margin-right: .8rem">取消</a-button>
      </a-popconfirm>
      <a-button @click="handleSubmit" type="primary" :loading="loading">提交</a-button>
    </div>
  </a-drawer>
</template>
<script>
const formItemLayout = {
  labelCol: { span: 4 },
  wrapperCol: { span: 18 }
}
export default {
  name: 'CategoryAdd',
  props: {
    categoryAddVisiable: {
      default: false
    }
  },
  data () {
    return {
      loading: false,
      formItemLayout,
      form: this.$form.createForm(this),
      category: {},
      fileList: [],
      enable: { status: true }
    }
  },
  methods: {
    statusChange (checked) {
      this.enable.status = checked
    },
    reset () {
      this.loading = false
      this.category = {}
      this.form.resetFields()
      this.enable = {status: true}
    },
    onClose () {
      this.reset()
      this.$emit('close')
    },
    setValue () {
      if (this.enable.status === true) {
        this.category.status = 'ENABLE'
      } else {
        this.category.status = 'DISABLE'
      }
    },
    handleSubmit () {
      this.setValue()
      this.form.validateFields((err, values) => {
        if (!err) {
          let category = this.form.getFieldsValue()
          category.status = this.category.status
          this.$post('category', {
            ...category
          }).then(result => {
            if (result.data.code === '1') {
              this.reset()
              this.$emit('success')
            } else {
              this.$message.error('新增失败')
            }
          }).catch((data) => {
            this.loading = false
            this.$message.error('新增失败')
          })
        }
      })
    }
  }
}
</script>
